import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/welcome/Welcome.vue'
import Users from '../components/users/users.vue'
import PowerList from '../components/power/powerlist.vue'
import RoleList from '../components/power/rolelist.vue'
import Category from '../components/goods/category.vue'
import GoodsParams from '../components/goods/goodparams.vue'
import GoodList from '../components/goods/goodlist.vue'
import AddGoods from '../components/goods/addgoods.vue'
import Orders from '../components/orders/orders.vue'
import Reports from '../components/reports/index.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'form-login', component: Login },
  {
    path: '/home',
    name: 'user-home',
    component: Home,
    children: [
      { path: '/home', redirect: '/index' },
      { path: '/index', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: PowerList },
      { path: '/roles', component: RoleList },
      { path: '/categories', component: Category },
      { path: '/params', component: GoodsParams },
      { path: '/goods', component: GoodList },
      { path: '/goods/addgood', component: AddGoods },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 重复点击导航时，控制台出现报错 ，虽然不影响功能使用，但也不能视而不见
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const token = sessionStorage.getItem('token')
  token ? next() : next('/login')
})

export default router
